package com.wheesper.www.WheesperServer.Net.Chat;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;

import com.Wheesper.www.WheesperServer.Model.Group;
import com.Wheesper.www.WheesperServer.Model.Group.Member;
import com.Wheesper.www.WheesperServer.Model.User;
import com.Wheesper.www.WheesperServer.Model.UserCenter;
import com.google.protobuf.InvalidProtocolBufferException;
import com.wheesper.www.WheesperServer.Common.OfflineMessageTrusteeship;
import com.wheesper.www.WheesperServer.Net.Session.*;
import com.wheesper.www.WheesperServer.Services.LogController;

import ProtocolBuffer.ProtoMessageOuterClass.ProtoMessage;

public class ChatRoom {
	private final Integer _chatRoomId;
	private Set<Session> _sessions;
	private Set<User> _offline_users;
	
	public ChatRoom(Group group) {
		this._chatRoomId = group.ID();
		_sessions = new HashSet<Session>();
		_offline_users = new HashSet<User>();
		group.Members().forEach(new Consumer<Group.Member>() {
			@Override
			public void accept(Member mem) {
				User user = UserCenter.Instance().UserObject(mem.Email());
				_offline_users.add(user);
			}
		});
	}
	
	public void register(Session session) {
		User user = LogController.Instance().GetOnlineUserBy((IOSession)session);
		_offline_users.remove(user);
		_sessions.add(session);
	}
	
	public void deregister(Session session) {
		User user = LogController.Instance().GetOnlineUserBy((IOSession)session);
		_offline_users.add(user);
		_sessions.remove(session);
	}
	
	public void broadCastToAll(final byte[] msg) {
		_sessions.forEach(new Consumer<Session>() {
			@Override
			public void accept(Session peer) {
				peer.writeToRemote(msg);
			}
		});
		
		_offline_users.forEach(new Consumer<User>() {
			@Override
			public void accept(User user) {
				ProtoMessage message;
				try {
					message = ProtoMessage.parseFrom(msg);
					OfflineMessageTrusteeship.Instance().trusteeFor(user,message );
				} catch (InvalidProtocolBufferException e) {
					e.printStackTrace();
				}
			}			
		});
	}

	public Integer getID() {
		return _chatRoomId;
	}
}
